<template>
  <div>
    <!-- <el-dialog :title="'给'+billingData.customerName+'开单'" :visible.sync="modalShow" width="60%" :before-close="modalClose" center> -->
    <el-dialog title="开单" :visible.sync="modalShow" width="60%" :before-close="modalClose" center>
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="顾客" prop="customerName">
          <!-- <el-input v-model="ruleForm.customerData" style="width:40%" @focus="selectCustomers" /> -->
          <el-select v-model="ruleForm.customerName" filterable placeholder="请选择" style="width:40%">
            <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item" />
          </el-select>
        </el-form-item>
        <div>挑选</div>
        <el-container>
          <el-aside width="195x">
            <LeftClassification :tabs-text="tabsText" :get-url="getUrl" @classificationClist="getClassificationId" @tabsVales="handleTabs" />
          </el-aside>
          <el-main>
            <div v-show="tabsBool===1">
              <el-input v-model="search" placeholder="请输入名称和拼音码" style="width:30%" @input="searchData" />
              <el-table ref="multipleTablem" :data="tableData1" style="width: 100%">
                <el-table-column label="名称" prop="dataName" align="center" />
                <el-table-column prop="pinyinCode" label="拼音码" align="center" />
                <!-- <el-table-column prop="projectDuration" label="套餐期限" align="center" show-overflow-tooltip /> -->
                <el-table-column prop="price" label="套餐价格" align="center" />
                <el-table-column prop="stopData" label="操作" align="center">
                  <template slot-scope="{ row }">
                    <el-button type="text" @click="seeDetails(row)">详情</el-button>
                    <el-checkbox @change="handlechange1($event,row)" />
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-show="tabsBool===2">
              <el-input placeholder="请输入名称和拼音码" style="width:30%" />
              <el-table ref="multipleTable" :data="tableData2" tooltip-effect="dark" style="width: 100%" @select="handlechange2">
                <el-table-column label="名称" prop="name" align="center" />
                <el-table-column prop="pinyinCode" label="拼音码" align="center" />
                <el-table-column prop="projectDuration" label="属性" align="center" show-overflow-tooltip />
                <el-table-column prop="stopData" label="规格" align="center" show-overflow-tooltip />
                <el-table-column prop="specifications" label="单位" align="center" show-overflow-tooltip />
                <el-table-column prop="price" label="使用次数" align="center" show-overflow-tooltip />
                <el-table-column prop="price" label="售价" align="center" show-overflow-tooltip />
                <el-table-column type="selection" label="操作" align="center" width="55" />
              </el-table>
            </div>
            <div v-show="tabsBool===3">
              <el-input placeholder="请输入名称和拼音码" style="width:30%" />
              <el-table ref="multipleTablem" :data="tableData3" tooltip-effect="dark" style="width: 100%" @select="handlechange3">
                <el-table-column label="名称" prop="name" align="center" />
                <el-table-column prop="pinyinCode" label="拼音码" align="center" />
                <el-table-column prop="stopData" label="规格" align="center" show-overflow-tooltip />
                <el-table-column prop="specifications" label="单位" align="center" show-overflow-tooltip />
                <el-table-column prop="price" label="售价" align="center" show-overflow-tooltip />
                <el-table-column type="selection" label="操作" align="center" width="55" />
              </el-table>
            </div>
          </el-main>
        </el-container>
        <div>
          <ul v-if="selectTables.length>0">
            <li class="detailed">
              商品清单：
            </li>
            <li v-for="(items,i) of selectTables" :key="i">
              <el-row style="width:5%">
                <el-col>
                  <el-checkbox v-model="items.checkeds" @change="handleChecked(items.checkeds,items.id)" />
                </el-col>
                <el-col>
                  <el-button type="text" @click="handleDelete(items.id)"><i class="el-icon-close" /></el-button>
                </el-col>
              </el-row>
              <el-row style="width:95%">
                <el-row type="flex">
                  <el-col :span="20" class="product">
                    <el-button class="bg" type="text">{{ items.productAttrib }}</el-button>
                    <p v-if="items.productAttrib!=='套餐类'" style="margin:0px 10px;">{{ items.printName }}</p>
                    <p v-if="items.productAttrib==='套餐类'" style="margin:0px 10px;">{{ items.classifyName }}</p>
                    <el-button v-if="items.productAttrib==='套餐类'" class="bg" type="text" @click="seeDetails(items)">详情</el-button>
                  </el-col>
                  <el-col :span="3">
                    <el-input-number v-model="items.contentCount" :min="1" :max="10" label="描述文字" @change="handleChangeNum" />
                  </el-col>
                </el-row>
                <el-row v-if="items.productAttrib!=='套餐类'" class="grey" type="flex">
                  <el-col :span="20">
                    <span>规格：{{ items.specifications }}</span>
                    <span>单位：{{ items.unit }}</span>
                    <span>使用次数：{{ items.usageTimes }}</span>
                  </el-col>
                  <el-col :span="4">
                    <span>可用库存：{{ items.availableStock }}</span>
                  </el-col>
                </el-row>
                <el-row type="flex" class="price">
                  <el-col :span="6">
                    售价：￥{{ items.price }}
                  </el-col>
                  <el-col :span="6">
                    主治医生：
                    <el-select v-model="items.attendingDoctor" placeholder="请选择" style="width:50%">
                      <el-option v-for="item in items.options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-col>
                  <el-col :span="2">
                    <el-checkbox v-model="items.discount" @change="handleDiscount(items.discount,items.id)">折扣</el-checkbox>
                  </el-col>
                  <el-col v-if="items.discount" :span="5">
                    折扣率：
                    <el-input v-model="items.discountRate" style="width:40%" @input="discountChange(items)" />
                    %
                  </el-col>
                  <el-col v-if="items.discount" :span="5">
                    折后价：
                    <el-input v-model="items.discountPrice" style="width:40%" />
                  </el-col>
                </el-row>
              </el-row>
            </li>
          </ul>
          <el-row v-if="selectTables.length>0">
            <el-col :offset="18" :span="6">总额：￥{{ $store.state.billing.allPrice1 }}</el-col>
            <el-col :offset="18" :span="6">优惠：-￥{{ discountPrice }}</el-col>
            <el-col :offset="17" :span="7">合计：<span class="span">￥{{ setMealPrice }}</span></el-col>
          </el-row>
          <el-row type="flex">
            <el-col :span="3">
              付款方式：
            </el-col>
            <el-col :span="22">
              <el-radio v-model="paymentType" label="全款" />
              <el-radio v-model="paymentType" label="定金">定金+尾款</el-radio>
            </el-col>
          </el-row>
          <el-row v-if="paymentType==='定金'">
            <el-col :span="2">
              定金支付
            </el-col>
            <el-col :span="6">
              <el-input v-model="depositAmount" style="width:50%" @input="componentBalance" />元
            </el-col>
            <el-col :span="6">
              尾款需要支付 {{ balancePayment }}元
            </el-col>
          </el-row>
        </div>
        <el-form-item>
          <el-row type="flex">
            <el-col :span="3" :offset="8">
              <el-button plain @click="handlerSubmit('ruleForm')">提交</el-button>
            </el-col>
            <el-col :span="3" :offset="2">
              <el-button plain @click="cancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <el-dialog width="40%" title="套餐详情" :visible.sync="innerVisible" append-to-body>
        <mealDetails :details-id="detailsId" />
      </el-dialog>
    </el-dialog>
  </div>

</template>

<script>
import { mapMutations } from 'vuex';
import LeftClassification from "@/components/leftClassification";
import mealDetails from "@/components/mealDetails";
export default {
  name: "Index",
  components: {
    LeftClassification,
    mealDetails,
  },
  props: {
    billingData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      tabsText: [
        { label: '套餐', name: 'meal' },
        { label: '项目', name: 'product' },
        { label: '物品', name: 'drugs' },
      ],
      getUrl: 'doctor/consulting/getAllComboList',
      tabsBool: 1,
      allPrice: 0,
      search: '',
      searchVal: {},
      discountPrice: 0,
      setMealPrice: 0,
      paymentType: '全款',
      discount: true,
      innerVisible: false,
      modalShow: false,
      numb: 0.8,
      ruleForm: {},
      detailsId: [],
      rules: {
        customerName: [// 主要需求
          { required: true, message: '请选择顾客', trigger: 'change' },
        ],
      },
      tableData1: [],
      tableData2: [],
      tableData3: [],
      selectTableData1: [],
      selectTableData2: [],
      selectTableData3: [],
      selectTables: [],
      depositAmount: 0,
      balancePayment: 0,
      options: [],
      option: [],
      idList: [], // 是否折扣的数组
      checkedIdList: [], // 商品是否被勾选
    };
  },
  computed: {
    userInfo() {
      return this.$store.getters.currentUserInfo;
    },
  },
  watch: {
    billingData: {
      handler(newVal) {
        this.ruleForm = newVal;
        console.log("变化");
      },
    },
    selectTables: {
      handler(val) {
        let allPrice = 0;
        let discountPrice = 0;
        let setMealPrice = 0;
        val.forEach(item => {
          if (item.checkeds) {
            allPrice += Math.floor((item.contentCount * item.price).toFixed(2) * 100) / 100;
            setMealPrice += Math.floor((item.contentCount * item.discountPrice).toFixed(2) * 100) / 100;
          }
        });
        discountPrice = Math.floor((allPrice - setMealPrice).toFixed(2) * 100) / 100;
        this.allPrice = allPrice;
        this.discountPrice = discountPrice;
        this.setMealPrice = setMealPrice;
        this.ruleForm.price = setMealPrice;
        this.ruleForm.originalPrice = allPrice;
        this.ruleForm.discountPrice = discountPrice;
        this.balancePayment = (Number(this.allPrice) - Number(this.depositAmount)).toFixed(2) * 100 / 100;
      },
      deep: true,
    },
  },
  mounted() {
    this.selectCustomers();
    this.fetchHospital();
    this.ruleForm = this.billingData;
  },
  methods: {
    searchData() {
      console.log(this.searchVal);
      this.getClassificationId(this.searchVal);
    },
    componentBalance() {
      this.depositAmount = this.depositAmount.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符
      this.depositAmount = this.depositAmount.replace(/^\./g, ""); // 验证第一个字符是数字而不是.
      this.depositAmount = this.depositAmount.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
      this.depositAmount = this.depositAmount.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      this.depositAmount = this.depositAmount.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');// 只能输入两个小数
      this.balancePayment = (Number(this.allPrice) - Number(this.depositAmount)).toFixed(2) * 100 / 100;
    },
    async selectCustomers() {
      const res = await this.$api['customer/customers/list']();
      if (res.code !== 200) return this.$message.error('查询顾客失败！');
      this.option = [];
      res.data.result.forEach((item, i) => {
        this.option[i] = { value: item.id, label: item.name };
      });
    },
    discountChange(item) {
      item.discountRate = parseInt(item.discountRate);
      const discountPrice = item.price * item.discountRate / 100;
      this.$set(item, 'discountPrice', Math.floor(discountPrice * 100) / 100);
    },
    cancel() {
      this.$emit('cancels');
    },
    seeDetails(row) {
      this.detailsId = row.id;
      this.innerVisible = true;
    },
    async fetchHospital() { // 获取医生
      const res = await this.$api['doctor/consulting/hisusrjobSelect']({ "hospitalJobName": "主治医生" });
      if (res.code !== 200) return this.$message.error('查询医生失败！');
      this.options = [];
      res.data.forEach((item, i) => {
        this.options[i] = { value: item.id, label: item.usrName };
      });
    },
    async handleDelete(id) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      } else {
        this.selectTables.forEach((item, i) => {
          if (item.id === id) {
            this.selectTables.splice(i, 1);
          }
        });
        this.tableData2.forEach(row => {
          if (id === row.id) {
            this.$refs.multipleTable.toggleRowSelection(row, false);
          }
        });
        return this.$message.success('已删除成功');
      }
    },
    handleTabs(val) {
      if (val === 'meal') {
        this.tabsBool = 1;
      } else if (val === 'product') {
        this.tabsBool = 2;
      } else {
        this.tabsBool = 3;
      }
    },
    async getClassificationId(val) {
      // 查询提交的产品分类id
      this.searchVal.productClassificationId = val.list.join(",");
      if (this.tabsBool === 1) {
        const res = await this.$api['doctor/consulting/comboList']({ query: this.searchVal });
        if (res.code !== 200) return this.$message.error('查询套餐列表失败！');
        this.tableData1 = res.data;
        this.tableData1.forEach(item => {
          this.$set(item, 'contentCount', 1);
          this.$set(item, 'discountRate', '100');
          this.$set(item, 'discountPrice', item.price);
          this.$set(item, 'attendingDoctor', '');
        });
      } else if (this.tabsBool === 2) {
        const res = await this.$api['doctor/consulting/productList']({ query: this.searchVal });
        if (res.code !== 200) return this.$message.error('查询项目列表失败！');
        this.tableData2 = res.data;
        this.tableData2.forEach(item => {
          this.$set(item, 'contentCount', 1);
          this.$set(item, 'discountRate', '100');
          this.$set(item, 'discountPrice', item.price);
          this.$set(item, 'attendingDoctor', '');
        });
      } else if (this.tabsBool === 3) {
        const res = await this.$api['data/drugs/drugsList']({ query: this.searchVal });
        if (res.code !== 200) return this.$message.error('查寻物品列表失败！');
        this.tableData3 = res.data;
        this.tableData3.forEach(item => {
          this.$set(item, 'contentCount', 1);
          this.$set(item, 'discountRate', '100');
          this.$set(item, 'discountPrice', item.sellPrice);
          this.$set(item, 'price', item.sellPrice);
          this.$set(item, 'attendingDoctor', '');
        });
      }
    },
    ...mapMutations({
      addPriceMutations: 'billing/ADD_PRICE_MUTATIONS',
    }),
    init() {
      this.modalShow = true;
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
      });
    },
    handlerSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var selectTable = this.selectTables.filter(function(item) {
            if (item.checkeds) {
              return item;
            }
          });
          this.ruleForm.orderList = selectTable;
          this.option.forEach(item => {
            if (typeof (this.ruleForm.customerName) !== 'object') {
              if (this.ruleForm.customerName === item.label) {
                this.$set(this.ruleForm, 'customerName', item.label);
                this.$set(this.ruleForm, 'customerId', item.value);
              }
            } else {
              if (this.ruleForm.customerName.label === item.label) {
                this.$set(this.ruleForm, 'customerName', item.label);
                this.$set(this.ruleForm, 'customerId', item.value);
              }
            }
          });
          this.ruleForm.orderPaymentStyle = this.paymentType;
          this.ruleForm.depositAmount = this.depositAmount;
          this.ruleForm.balancePayment = this.balancePayment;
          this.ruleForm.createdBy = this.userInfo.name;
          this.$nextTick(() => {
            this.$api['doctor/consulting/addOrder'](this.ruleForm).then(res => {
              if (res.code !== 200) return;
              this.$message.success('开单成功');
              this.$emit('cancels');
            });
          });
        } else {
          return false;
        }
      });
    },
    handleChangeNum(value) {
      this.addPriceMutations([...this.selectTableData1, ...this.selectTableData2, ...this.selectTableData3]);
    },
    handlechange1(bool, row) {
      if (bool) {
        this.selectTableData1.push(row);
      } else {
        this.selectTableData1.forEach((item, i) => {
          if (item.classifyId === row.classifyId) {
            this.selectTableData1.splice(i, 1);
          }
        });
      }
      this.selectTableData1.forEach(item => {
        item.projectId = item.id;
        item.projectName = item.dataName;
        item.productNo = item.no;
        item.contentType = item.dataName;
        this.$set(item, 'productAttrib', '套餐类');
        this.$set(item, 'discount', false);
        this.$set(item, 'checkeds', true);
        this.$set(item, 'options', this.options);
      });
      this.selectTables = [];
      this.selectTables.push(...this.selectTableData1, ...this.selectTableData2, ...this.selectTableData3);
      this.handleDiscount(false, row.id);
      this.discountInit();
      this.handleChecked(true, row.id);
      this.checkedInit();
      this.addPriceMutations([...this.selectTableData1, ...this.selectTableData2, ...this.selectTableData3]);
    },
    handlechange2(selection, row) {
      this.selectTableData2 = selection;
      this.selectTableData2.forEach(item => {
        item.projectId = item.id;
        item.projectName = item.name;
        item.productNo = item.no;
        item.contentType = item.name;
        item.usageCount = item.usageTimes;
        item.specl = item.specifications;
        this.$set(item, 'productAttrib', '项目类');
        this.$set(item, 'discount', false);
        this.$set(item, 'checkeds', true);
        this.$set(item, 'options', this.options);
      });
      this.selectTables = [];
      this.selectTables.push(...selection, ...this.selectTableData1, ...this.selectTableData3);
      this.handleDiscount(false, row.id);
      this.discountInit();
      this.handleChecked(true, row.id);
      this.checkedInit();
      this.addPriceMutations([...selection, ...this.selectTableData1, ...this.selectTableData3]);
    },
    handlechange3(selection, row) {
      this.selectTableData3 = selection;
      this.selectTableData3.forEach(item => {
        item.projectId = item.id;
        item.projectName = item.name;
        item.productNo = item.no;
        item.contentType = item.name;
        item.specl = item.spec;
        item.price = item.sellPrice;
        this.$set(item, 'productAttrib', '物品类');
        this.$set(item, 'discount', false);
        this.$set(item, 'checkeds', true);
        this.$set(item, 'options', this.options);
      });
      this.selectTables = [];
      this.selectTables.push(...selection, ...this.selectTableData1, ...this.selectTableData2);
      this.handleDiscount(false, row.id);
      this.discountInit();
      this.handleChecked(true, row.id);
      this.checkedInit();
      this.addPriceMutations([...selection, ...this.selectTableData1, ...this.selectTableData2]);
    },
    discountInit() {
      this.selectTables.forEach(outItem => {
        this.idList.forEach(inItem => {
          if (outItem.id === inItem) {
            this.$set(outItem, 'discount', true);
          }
        });
      });
    },
    checkedInit() {
      this.selectTables.forEach(outItem => {
        this.checkedIdList.forEach(inItem => {
          if (outItem.id === inItem) {
            this.$set(outItem, 'checkeds', false);
          }
        });
      });
    },
    handleDiscount(bool, id) { // 点击折扣
      if (bool) {
        this.idList.push(id);
      } else {
        this.idList.forEach((item, i) => {
          if (item === id) {
            this.idList.splice(i, 1);
            i--;
          }
        });
      }
    },
    handleChecked(bool, id) { // 点击商品旁的checked-box
      if (!bool) {
        this.checkedIdList.push(id);
      } else {
        this.checkedIdList.forEach((item, i) => {
          if (item === id) {
            this.checkedIdList.splice(i, 1);
            i--;
          }
        });
      }
    },
    modalClose() {
      this.modalShow = false;
    },
  },
};
</script>

<style scoped lang='scss'>
@import './billing.scss';
.el-row,
span {
  line-height: 40px;
}
li {
  display: flex;
  margin-top: 5px;
}
</style>
